#encoding=utf-8
'''
Created on 2015-3-29

@author: cooler
'''
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')

import  logging,  os.path
import math, time
from datetime import datetime, timedelta
import math,re
import traceback
import hashlib
import base64
from werkzeug import secure_filename
from bson.objectid import ObjectId

from flask import Blueprint, render_template, make_response, request, redirect,url_for, session, abort, current_app
from flask import g,jsonify
from flask_principal import Principal, Permission, UserNeed, RoleNeed, Identity, AnonymousIdentity, identity_changed, identity_loaded

from service.auth import user
from service.authority import *
from service.models import *
from utils.CheckSign import init_salt,init_password,init_api_key,init_secret_key

logger = logging.getLogger('user')
logger.setLevel(logging.DEBUG)


@user.route("/user_wallet_show",methods=['POST','GET'])
@admin_permission.require(http_exception=401)
def user_wallet_show():
    gateio_info_list = Gateio_info.objects(user_info=g.user_info).all()
    datas = {
        "gateio_info_list":gateio_info_list,
    }
    return render_template('user/user_wallet_list.html',datas=datas,user_info = g.user_info)

@user.route('/user_wallet_list', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def user_wallet_list():
    page = int(g.args.get("page",1))
    pnum = int(g.args.get("limit",20))
    data = []
    total = 0
    user_wallet_list = Wallet.objects(user_info=g.user_info).all().skip((page-1)*pnum).limit(pnum)
    total = total + Wallet.objects(user_info=g.user_info).count()
    for user in user_wallet_list:
        data.append({
            "id":str(user['id']),
            "gateio":user['gateio_info']['name'],
            "name_cn":user['name_cn'],
            "amount":user['amount'],
            "status":user['status'],
            "ctime":user['ctime'].strftime("%Y-%m-%d %H:%M:%S"),
            "utime":user['utime'].strftime("%Y-%m-%d %H:%M:%S"),
        })
    results = {
        "code":0,
        "msg":"",
        "count":total,
        "data":data
        }
    # g.results['datas'] = user_wallet_list
    return jsonify(results)

@user.route("/gateio_user_show",methods=['POST','GET'])
@admin_permission.require(http_exception=401)
def gateio_user_show():
    datas = {
    }
    return render_template('user/gateio_user_show.html',datas=datas,user_info = g.user_info)


@user.route('/gateio_user_list', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def gateio_user_list():
    page = int(g.args.get("page",1))
    pnum = int(g.args.get("limit",20))
    data = []
    gateio_info_list = Gateio_info.objects(user_info=g.user_info).all().skip((page-1)*pnum).limit(pnum)
    total = Gateio_info.objects(user_info=g.user_info).count()
    for gateio in gateio_info_list:
        data.append({
            "id":str(gateio['id']),
            "name":gateio['name'],
            "phone":gateio['phone'],
            "email":gateio['email'],
            "status":gateio['status'],
            "ctime":gateio['ctime'].strftime("%Y-%m-%d %H:%M:%S"),
            "utime":gateio['utime'].strftime("%Y-%m-%d %H:%M:%S"),
        })
    results = {
        "code":0,
        "msg":"",
        "count":total,
        "data":data
        }
    return jsonify(results)

@user.route('/add_gateio_user', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def add_gateio_user():
    name = g.args.get("name","").strip()
    phone = g.args.get("phone","").strip()
    email = g.args.get("email","").strip()
    api_key = g.args.get("api_key","").strip()
    secret_key = g.args.get("secret_key","").strip()
    id_rsa = init_salt()
    id_rsa_pub = init_salt()
    gateio_info = Gateio_info.objects(user_info=g.user_info,name=name).first()
    if gateio_info:
        g.results['datas']["code"]=2
        g.results['msg'] = "you have this gateio account!"
    else:
        gateio_info = Gateio_info()
        gateio_info.user_info = g.user_info
        gateio_info.name = name
        gateio_info.phone = phone
        gateio_info.email = email
        gateio_info.api_key = api_key
        gateio_info.secret_key = secret_key
        gateio_info.id_rsa = id_rsa
        gateio_info.id_rsa_pub = id_rsa_pub
        gateio_info.save()
    return jsonify(g.results)

@user.route('/add_gateio_wallet', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def add_gateio_wallet():
    name_cn = g.args.get("name_cn","").strip()
    amount = g.args.get("amount","0").strip()
    oid = g.args.get("oid","").strip()
    objectid = ObjectId(oid)
    gateio_info = Gateio_info.objects(id=objectid).first()
    if gateio_info:
        wallet = Wallet.objects(gateio_info=gateio_info,user_info=g.user_info,name_cn=name_cn).first()
        if wallet:
            g.results['datas']["code"]=2
            g.results['msg'] = "you has been init wallet !"
        else:
            wallet = Wallet()
            wallet.user_info=g.user_info
            wallet.gateio_info=gateio_info
            wallet.name_cn=name_cn
            wallet.amount=float(amount)
            wallet.save()
    else:
        g.results['datas']["code"]=2
        g.results['msg'] = "please add gateio account"
    return jsonify(g.results)

@user.route('/change_gateio_user_info', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def change_gateio_user_info():
    oid = g.args.get("oid","").strip()
    objectid = ObjectId(oid)
    gateio_info = Gateio_info.objects(user_info=g.user_info,id=objectid).first()
    if gateio_info['status']==0:
        gateio_info.update(status=1)
    elif gateio_info['status']==1 :
        gateio_info.update(status=2)
    elif gateio_info['status']==2 :
        gateio_info.update(status=1)
    else:
        g.results['datas']['code']=2
        g.results['msg']='其他错误'
    return jsonify(g.results)

